<!--
 * @Author: your name
 * @Date: 2020-05-29 10:34:09
 * @LastEditTime: 2020-06-09 15:20:10
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \tuyibo\components\MyCollect.vue
--> 
<template>
  <section class="MyCollect">
    <div class="list-inner">
      <el-card class="box-card">
        <div slot="header" style="text-align:left;">
          <span class="card-title">我的收藏/{{count}}张</span>
        </div>
        <div v-if="count<=0">您未下载过任何图片!</div>
      
          <div class="photos">
            <div class="column" v-for="g in gridcount" :key="g">
              <div class="item" v-for="(ite,index) in photo_column[g-1]" :key="index">
                <div class="item-content">
                  <a @click="clickToDetail(ite.id)">
                    <img class="ite-img lazy" :data-src='ite.img_thumbnail|fillImgShot' @imgLoad="imgLoad" v-if="index>6">
                    <img class="ite-img" :src='ite.img_thumbnail|fillImgShot' @imgLoad="imgLoad" v-else>
                  </a>
                  <span class="add-to-basket">
                    <el-button type="text" icon="el-icon-delete" @click="uncollect(ite.id,photo_column[g-1],index)" title="移除收藏"></el-button>
                    <!-- <Button icon="ios-add" type="success" shape="circle" title="放入收藏篮" v-if="isShowBtnAddToBasket"></Button>
                    <Button icon="md-thumbs-up" type="success" shape="circle" title="点赞"></Button>
                    <Button icon="md-close" type="error" shape="circle" title="移出收藏篮" @click="uncollect(ite.id)"  v-if="isShowBtnRemoveFromBasket"></Button> -->
                  </span>
                </div>
              </div>
            </div>
          </div>
        </el-card> 
    </div>
    <div class="footer">
      <div class="gotop el-icon-top" v-show="gotop" @click="toTop">返回顶部</div>
    </div>
  </section>
</template>

<script>
export default {
  name: "MyCollect",
  data() {
    return {
      count: "",
      gotop: false,
      page: 1,
      pagesize: 30,
      gallery: [],
      defaultImg: 'this.src="' + require("../assets/images/loading.gif") + '"',
      flag: true,
      userid: "",

      items:[],
      flexinit:false,
      gridcount:0,
      islayout:false,
      lazyloadThrottle:-1,      
      imgList:[],
      photo_column:{},

      height:0,
      isShowBtnRemoveFromBasket:true,
      isShowBtnAddToBasket:true
    };
  },
  mounted() {
    if (window.sessionStorage.getItem("tuyibo_userid") !== null) {
      var data = JSON.parse(window.sessionStorage.getItem("tuyibo_userid"));
      this.userid = data.userid;
      this.load(this.userid);
    }
    // window.addEventListener("scroll", this.onScroll, true);
    // window.addEventListener("scroll", this.handleScroll, true);
    
    let swidth = this.$el.offsetWidth
    this.gridcount = parseInt(swidth/160)

    window.onresize = (e)=>{
      if( this.flexinit ) return;
      let w = parseInt(this.$el.offsetWidth / 160 )
      // console.log(w)
      if( w > this.gridcount || this.gridcount > w){
        this.flexinit = true
        this.gridcount = w
        setTimeout(()=>{
          this.loaddata(this.gallery);
        })
      }
    }
  },
  methods: {
    close(id, i) {
      this.$axios
        .post("api/web/collectPicture", { uid: this.userid, image_id: id })
        .then(res => {
          if (res.data.code == -1) {
            this.gallery.splice(i, 1);
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    handleScroll() {
      var scrolltop=document.documentElement.scrollTop||document.body.scrollTop
      scrolltop > 30 ? (this.gotop = true) : (this.gotop = false);
    },
    toTop() {
      window.scrollTo(0, 0);
    },
    onScroll() {
      // // 可滚动容器的高度
      // let innerHeight = document.querySelector("#__nuxt").clientHeight;
      // // 屏幕尺寸高度
      // let outerHeight = document.documentElement.clientHeight;
      // // 可滚动容器超出当前窗口显示范围的高度
      // let scrollTop =
      //   document.documentElement.scrollTop ||
      //   window.pageYOffset ||
      //   document.body.scrollTop;
      // // scrollTop在页面为滚动时为0，开始滚动后，慢慢增加，滚动到页面底部时，出现innerHeight <= (outerHeight + scrollTop)的情况，严格来讲，是接近底部。
      // // console.log('可滚动容器的高度:' + innerHeight, '屏幕尺寸高度:' + outerHeight, '可滚动容器超出当前窗口显示范围的高度:' + scrollTop)
      // console.log(outerHeight+scrollTop,innerHeight)
      // if (outerHeight + scrollTop >= innerHeight) {
      //   if (this.count > this.gallery.length) {
      //     // 加载更多操作
      //     this.showLoading = true;
      //     this.page += 1;
      //     this.load(this.userid);
      //   }
      // }

      if( this.flexinit ) return;
      let y = document.documentElement.scrollHeight - document.documentElement.scrollTop -1
      let ry = Math.round((document.documentElement.scrollHeight-document.documentElement.scrollTop)/document.documentElement.clientHeight)
      if (this.lazyloadThrottle) {
        clearTimeout(this.lazyloadThrottle);
      }

      this.lazyloadThrottle = setTimeout(() => {
        let fristlazy = document.querySelector("img.lazy")
        if( fristlazy !== null ){
          let p = fristlazy.parentElement.parentElement; 
          if( y - p.offsetTop < 600 ){
            // console.log(fristlazy.offsetTop, y )
            let lazyloadImages = document.querySelectorAll("img.lazy")
            lazyloadImages.forEach(function (img) {
              img.src = img.dataset.src
              img.classList.remove('lazy')
            })
          }
        }
      }, 20)
      if( !this.islayout && ry == 3 ){
        this.islayout = true
        this.layout()
      }
      if (  y < document.documentElement.clientHeight) {
        if(this.gallery.length>=this.count) return
        this.flexinit = true
        this.page++
        this.load(this.userid);
      }
    },
    layout(w){
      if( this.gridcount <= 1 ) return;
      let loop = true
      let hh = this.getColumnsHeight().sort()
      let cc = 1
      
      while(loop && cc < 5){
        //最大的一列挪到最小的去
        let maxidx = hh.length-1
        if( hh[maxidx][0] - hh[0][0] < 300 ) {
          loop = false
          return
        }
        let maxh = hh[maxidx]
        let moveitem = this.photo_column[maxh[1]].splice(this.photo_column[maxh[1]].length-1, 1)[0]
        this.photo_column[ hh[0][1] ].push( moveitem )
        hh[maxidx][0] -= moveitem.height
        hh[0][0] += moveitem.height
        hh = hh.sort()
        cc++
      }
    }, 

    loaddata(items){
      //获取宽度
      let column = {}
      let sumHeightArr = this.getColumnsHeight()
      for( let n = 0; n<items.length;n++){
        let item = items[n]
        let k = (n%this.gridcount)
        if( sumHeightArr[k][0] > 0 ){
          //console.log(sumHeightArr[k][1], k)
          k = sumHeightArr[k][1]
        }
        if( column[k] == undefined ){
          column[k] = []
        }
        column[k].push(item)
      }
      this.photo_column = column
      this.flexinit = false
      this.items = items
    },
    imgLoad(){
      this.ite.height = this.$el.offsetHeight
    },
    uncollect(id,list,i) {
      if (window.sessionStorage.getItem("tuyibo_userid") !== null) {
        var data = JSON.parse(window.sessionStorage.getItem("tuyibo_userid"));
        this.$axios.post("/api/web/collectPicture", {
            uid: data.userid,
            image_id: id
          }).then(res => {
            if (res.data.code == -1) {
              this.$message.info("移除收藏");
              list.splice(i,1)
              this.count--
            } else {
              this.$message.success(res.data.msg);
            }
            // this.load(this.bodyData);
          }).catch(err => {
            console.log(err);
          });
      } else if( window.loginbox ){
        window.loginbox.show = true
      }
    },
    load(userid) {
      this.showLoading = true;
      let page = this.page;
      let pagesize = this.pagesize;
      this.$axios
        .post("/api/web/getMyCollect", {
          userid,
          page,
          pagesize
        })
        .then(res => {
          this.showLoading = false;
          this.gallery.push(...res.data.rows);
          this.flag = true;

          this.count = res.data.count;
          this.loaddata(this.gallery)
          this.islayout = false
        })
        .catch(err => {
          console.log(err);
        });
    },
    getColumnsHeight(){
      let sumHeightArr = []
      let columns = this.$el.querySelectorAll('.column')
      Array.from(columns).forEach( (c, idx) => {
        let childs = Array.from(c.childNodes)
        let sumHeight = childs.reduce( (x,y) => y.offsetHeight + x, 0)
        sumHeightArr.push([sumHeight, idx])
      })
      return sumHeightArr
    },
    clickToDetail(id) {
      this.$router.push(`/detail?id=${id}`);
    }
  },
  activated(){
    window.addEventListener("scroll", this.onScroll, true);
    window.addEventListener("scroll", this.handleScroll, true);
  },
  deactivated() {
    window.removeEventListener("scroll", this.onScroll, true);
    window.removeEventListener("scroll", this.handleScroll, true);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!-- 该瀑布流插件安装方法：https://www.npmjs.com/package/vue-masonry  https://masonry.desandro.com/options.html-->

<style scoped lang="less">
.MyCollect {
  position: relative;
  padding-top: 24px;
  height: 800px;
  // overflow: auto;
  .list-inner {
    padding: 0 16px;
    position: relative;
    .photos{
      display: flex;
      width: 100%;
      position: relative;
      // padding: 20px 0 20px 20px;
      .column{
        display: block;
        flex-basis: 0;
        flex-grow: 1;
        flex-shrink: 1;
        margin-right: 10px;
        .item {
          padding: 5px;
          margin-top:10px;
          .item-content {
            overflow: hidden;
            position: relative;
            z-index: 1;
            cursor: pointer;
            > a {
              display: block;
              >img{
                display:block;
                width:100%;
              }
              .lazy{
                background: #F1F1FA;
                width: 160px;
                min-height: 200px;
                display: block;
                margin: 10px auto;
                border: 0;
              }
            }
            .add-to-basket {
              font-size: 20px;
              position: absolute;
              right: 0px;
              top: -10px;
              transition: all .2s;
              transform: scale(0);
            }
          }
          &:hover{
            .add-to-basket {
              transform: scale(1);
            }
          }
        }
      }
    }
  }
  .footer {
    position: fixed;
    right: 50px;
    bottom: 30px;
    z-index: 1000;
    .gotop {
      text-align: center;
      cursor: pointer;
      padding: 10px;
      border-radius: 5px;
      background: white;
      color: #000000;
      z-index: 1000;
    }
  }
}
</style>
